Skip to main content

Overview

The ClipLoss class implements the symmetric cross-entropy loss used to train CLIP models. It computes contrastive loss between image and text features by treating each image-text pair as a positive match and all other pairs in the batch as negatives. The loss is computed as the average of:
  • Image-to-text classification loss
  • Text-to-image classification loss
Key features:
  • Distributed training support - Efficient all-gather operations across GPUs
  • Local loss option - Compute loss only on local batch for memory efficiency
  • Label caching - Cache ground truth labels for faster training
  • Horovod support - Alternative distributed backend

Class Definition

Initialization Parameters

bool
default:"False"
If True, computes loss only between local image features and gathered text features (and vice versa). Reduces memory usage in distributed training but changes the gradient dynamics.
bool
default:"False"
If True, gathers features with gradient flow enabled. Required for certain distributed training strategies but increases memory usage.
bool
default:"False"
If True, caches ground truth labels to avoid recomputing them each forward pass. Saves computation at the cost of memory.
int
default:"0"
Current process rank in distributed training. Should match the rank from your distributed backend.
int
default:"1"
Total number of processes in distributed training. Set to 1 for single-GPU training.
bool
default:"False"
If True, uses Horovod for distributed operations instead of torch.distributed.

Attributes

  • local_loss: Whether local loss mode is enabled
  • gather_with_grad: Whether gradient flows through gather operations
  • cache_labels: Whether label caching is enabled
  • rank: Current process rank
  • world_size: Total number of processes
  • use_horovod: Whether using Horovod backend
  • prev_num_logits: Cached logits count for label caching
  • labels: Dictionary of cached label tensors per device

Key Methods

forward

Computes the contrastive loss. Parameters:
  • image_features: Normalized image features of shape (batch_size, embed_dim)
  • text_features: Normalized text features of shape (batch_size, embed_dim)
  • logit_scale: Temperature parameter (typically model.logit_scale.exp())
  • logit_bias: Optional bias term to add to logits
  • output_dict: If True, returns dict with key “contrastive_loss”, else returns scalar
Returns: Contrastive loss value (average of image-to-text and text-to-image losses)

get_logits

Computes similarity logits between image and text features. Handles distributed gathering if world_size > 1. Returns: Tuple of (logits_per_image, logits_per_text)

get_ground_truth

Generates or retrieves cached ground truth labels (diagonal identity matrix). Returns: Label tensor of shape (num_logits,) with values [0, 1, 2, …, num_logits-1]

Usage Example

Distributed Training Example

Local Loss Example

With Logit Bias

Dictionary Output

Performance Considerations

Memory vs. Accuracy Trade-offs: Best Practices:
  • Enable cache_labels=True for training (slight memory cost, faster)
  • Use local_loss=True only when memory is constrained
  • Set gather_with_grad=False for most use cases
  • Ensure features are normalized before passing to loss

Mathematical Formulation

Given normalized image features IRN×DI \in \mathbb{R}^{N \times D} and text features TRN×DT \in \mathbb{R}^{N \times D}:
  1. Compute logits: L=τ(IT)+bL = \tau \cdot (I \cdot T^\top) + b
    • τ\tau = logit_scale.exp()
    • bb = logit_bias (optional)
  2. Compute symmetric cross-entropy: L=12[CE(L,labels)+CE(L,labels)]\mathcal{L} = \frac{1}{2} \left[ \text{CE}(L, \text{labels}) + \text{CE}(L^\top, \text{labels}) \right] where labels = [0,1,2,...,N1][0, 1, 2, ..., N-1] (diagonal is positive)
  3. In distributed setting, features are gathered from all GPUs before computing logits
  • CLIP - Model that uses this loss
  • CoCaLoss - Extended loss with caption generation
  • SigLipLoss - Alternative sigmoid-based loss